<template>
  <div class="project-manage-new">
    <div class="project-manage-new-title">
      <div class="project-manage-new-title-left">{{ projectTitle }}</div>
      <div class="project-manage-new-title-right">
        <el-button class="ml_16" type="plain-third" @click="goBack">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="isSubmitLoading">{{ $t('common.base.save') }}</el-button>
      </div>
    </div>

    <div class="project-manage-new-form" v-loading.fullscreen.lock="showLoading">
      <form-builder v-if="fields.length && !showLoading" ref="formRef" :fields="fields" :value="form" mode="projectType" 
        :formStatus="formEditingMode"
        @update="update" 
        :formEditingMode="formEditingMode"
        @getDeleteFiles="getDeleteFiles">
        <template slot="product" slot-scope="{ field }">
          <form-item :label="field.displayName">
            <FormProjectProduct ref="projectProductRef" :value="form.product" :field="field" :customer="form.customer" :address="form.address" :linkman="form.linkman" @updateProduct="updateProduct" />
          </form-item>
        </template>

        <!-- 项目类型 -->
        <template slot="projectType" slot-scope="{ field }">
          <form-item :label="field.displayName">
            <form-select :disabledJustForSelect="field.disabled || isEdit" :field="field" :source="templateList" :value="typeTemplateId" :clearable="false" @input="chooseTemplate"></form-select>
          </form-item>
        </template>

        <!-- 计划开始时间 -->
        <template slot="planStartTime" slot-scope="{ field, value }">
          <form-item :label="field.displayName">
            <form-planstarttime :field="field" :value="value | fmt_form_date" @update="update" :picker-options="planStartPickerOptions"></form-planstarttime>
          </form-item>
        </template>

        <!-- 计划结束时间 -->
        <template slot="planEndTime" slot-scope="{ field, value }">
          <form-item :label="field.displayName">
            <form-planendtime :field="field" :value="value | fmt_form_date" @update="update" :picker-options="planEndPickerOptions"></form-planendtime>
          </form-item>
        </template>
      </form-builder>
    </div>
  </div>
</template>
<script>
import { onMounted, reactive, ref, toRefs, computed } from 'vue';

import i18n from '@src/locales';
import * as FormUtil from '@src/component/form/util';
import { toast } from '@src/util/platform';
import platform from '@src/platform';
import { scrollIntoFirstRequireDom } from '@src/util/dom';

import { getProjectTypeField, projectTypeList, saveProjectType, updateProjectType, projectTypeDetail } from '@src/api/ProjectManage.ts';

import FormProjectProduct from '@src/modules/projectManage/components/projectProduct.vue';

import useUpdate from '@src/modules/projectManage/productTypeUtils/update.js';
import { packToProjectType, packToProjectTypeForm } from '@src/modules/projectManage/productTypeUtils/projectTypeData.js';

import { jumpProjectTypeDetail, jumpPageProjectList, reloadTab } from '@src/modules/projectManage/productTypeUtils/jumpPage.js';
import { ConnectorModuleConnectorCreateProjectMixin } from '@src/modules/connector/mixin'
import { getCurrentInstance } from 'vue'
import { getDisabledDate } from 'pub-bbx-utils'

export default {
  name: 'project-manage-new',
  components: {
    FormProjectProduct,
  },
  mixins: [ConnectorModuleConnectorCreateProjectMixin],
  setup() {
    const formRef = ref();

    const state = reactive({
      isSubmitLoading: false,
      showLoading: false,
      fields: [],
      templateList: [],
      typeTemplateId: '',
      needServerDeleFiles: []
    });

    const { proxy } = getCurrentInstance()
    let { projectProductRef, update, updateProduct, updateState, fetchFormField } = useUpdate();

    // 通过关键字获取参数
    const getParamByUrl = key => {
      const url = new URL(location.href);
      return url.searchParams.get(key);
    };

    const majorKeyId = computed(() => {
      return getParamByUrl('id');
    });

    const templateId = computed(() => {
      return getParamByUrl('templateId');
    });
    const action = computed(() => {
      return getParamByUrl('action');
    });

    // 编辑
    const isEdit = computed(() => {
      return action.value === 'edit';
    });

    // 复制
    const isCopy = computed(() => {
      return action.value === 'copy';
    });

    const projectTitle = computed(() => {
      return isEdit.value ? i18n.t('common.projectManage.detail.editItem') : i18n.t('common.projectManage.detail.newItem');
    });

    const planStartPickerOptions = computed(() => {
      return {
        disabledDate(time) {
          return getDisabledDate(time, updateState.form.planEndTime)
        },
      };
    });

    const planEndPickerOptions = computed(() => {
      return {
        disabledDate(time) {
          return getDisabledDate(time, updateState.form.planStartTime, true)
        },
      };
    });

    const formEditingMode = computed(() => {
      return isEdit.value ? 'edit' : 'create';
    })

    // 获取模板列表
    const fetchTemplateList = async () => {
      try {
        let ret = await projectTypeList();

        const { success, message, data } = ret || {};

        if (!success) return toast(message, 'error');

        state.templateList = (data || []).map(item => {
          return {
            label: item.name,
            text: item.name,
            value: item.id + '',
          };
        });
      } catch (err) {
        console.log('error => fetchTemplateList', err);
      }
    };

    // 获取表单字段
    const fetchFields = async () => {
      state.showLoading = true;
      try {
        let ret = await getProjectTypeField({
          templateId: state.typeTemplateId,
          tableName: 'project',
        });

        const { success, message, data } = ret;
        if (!success) return toast(message, 'error');

        state.fields = (data || []).map(item => {
          return {
            ...item,
            // 项目名称限制100
            maxlength: item.fieldName == 'projectName' ? 100 : '',
          };
        });
        fetchFormField(state.fields);

        updateState.form = FormUtil.initialize(data, {});
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        state.showLoading = false;
      }
    };

    // 获取详情数据
    const fetchDetail = async () => {
      state.showLoading = true;
      try {
        let ret = await projectTypeDetail({
          id: majorKeyId.value,
        });

        const { success, message, data } = ret;
        if (!success) return toast(message, 'error');
        // 处理富文本
        const newData = await FormUtil.initRichTextContent(state.fields, data);
        updateState.form = packToProjectTypeForm(newData);
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        state.showLoading = false;
      }
    };

    // 选择模板
    const chooseTemplate = val => {
      state.typeTemplateId = val;
      fetchFields(val);
    };

    // 返回
    const goBack = () => {
      if (isEdit.value || isCopy.value) {
        jumpProjectTypeDetail({
          templateId: templateId.value,
          id: majorKeyId.value,
        });
      } else {
        reloadTab();
        jumpPageProjectList();
      }
    };

    // 保存表单字段
    const saveFields = async () => {
      state.isSubmitLoading = true;

      let params  = {
        ...packToProjectType(state.fields, updateState.form),
      }
      if (isCopy.value) {
        delete params.id
      }
      // 提交连接器参数
      try {
        proxy.setConnectorParamsForSubmit(params)
      } catch (error) {
        console.error(error)
      }

      try {
        let ret = await saveProjectType({
          templateId: state.typeTemplateId,
          ...params,
        });

        const { success, message, data } = ret;
        if (!success) return toast(message, 'error');

        // 连接器的话关闭当前弹窗
        try {
          const isInFrame = proxy.validateCurrentWindowIsInFrame()

          if (isInFrame) {
            proxy.removeConnectorCreateSessionData()
            proxy.postCloseDialogMessage()
            return
          } else {
            // 刷新列表页面
            let fromId = window.frameElement?.getAttribute('fromid');
            platform.refreshTab(fromId);
            // 跳转详情页面
            jumpProjectTypeDetail(data, true);
          }
        } catch (error) {
        console.error(error)
        }
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        state.isSubmitLoading = false;
      }
    };

    // 编辑保存
    const updateFields = async () => {
      state.isSubmitLoading = true;

      try {
        let ret = await updateProjectType({
          id: updateState.form.id,
          templateId: state.typeTemplateId,
          ...packToProjectType(state.fields, updateState.form),
          deleteFiles: state.needServerDeleFiles
        });

        const { success, message, data } = ret;
        if (!success) return toast(message, 'error');

        jumpProjectTypeDetail(data);
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        state.isSubmitLoading = false;
      }
    };

    // 保存提交
    const handleSubmit = () => {
      try {
        formRef.value.validate(false).then(valid => {
          scrollIntoFirstRequireDom(formRef.value);

          if (!valid) return false;

          if (isEdit.value) {
            updateFields();
          } else {
            saveFields();
          }
        });
      } catch (err) {
      } finally {
        state.isSubmitLoading = false;
      }
    };

    const updatePlanStartTime = val => {
      updateState.form.planStartTime = val;
    };

    const updatePlanEndTime = val => {
      updateState.form.planEndTime = val;
    };

    // 删除附件
    const getDeleteFiles = (files) => {
      state.needServerDeleFiles = [...state.needServerDeleFiles, ...files]
    }
    onMounted(async () => {
      state.typeTemplateId = templateId.value;
      fetchTemplateList();
      await fetchFields();
      // 编辑、复制的时候初始化数据
      if (isEdit.value || isCopy.value) {
        await fetchDetail();
      }
    });

    return {
      formRef,
      projectProductRef,
      ...toRefs(updateState),
      ...toRefs(state),
      goBack,
      handleSubmit,
      update,
      updateProduct,
      chooseTemplate,
      updatePlanStartTime,
      updatePlanEndTime,
      planStartPickerOptions,
      planEndPickerOptions,
      projectTitle,
      formEditingMode,
      getDeleteFiles,
      isCopy,
      isEdit
    };
  },
};
</script>
<style lang="scss">
.theme-default {
  padding: 12px;
}
</style>
<style lang="scss" scoped>
.project-manage-new {
  min-width: 1100px;
  height: 100%;
  background: #fff;
  border-radius: 4px;
  display: flex;
  flex-flow: column nowrap;
  overflow: hidden;
  &-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #e8e8e8;
    &-left {
      color: #262626;
      font-size: 16px;
      font-weight: 500;
    }
  }
  &-form {
    flex: 1;
    overflow: auto;
    .form-builder {
      padding: 0;
      margin: 24px auto 10px;
      max-width: 700px;
    }
  }
}
</style>